﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.IO;
using System.IO.Ports;
using System.Data.SqlClient;
using dateDealNamespace;
using serialPortNamespace;
using System.Threading;
using GDIPlusDemo;
using System.Runtime.InteropServices;
using System.Drawing.Drawing2D;


namespace GDIPlusDemo
{
    public partial class Form1 : Form
    {        
        #region 基类窗体样式 重绘
        public ToolTip _toolTip;

        public Form1(): base()
        {
            _toolTip = new ToolTip();
            FormExIni();
            _systemButtonManager = new SystemButtonManager(this);
            InitializeComponent();
        }

        internal ToolTip ToolTip
        {
            get { return _toolTip; }
        }
        
        #region 文件路径

        //窗体圆角矩形半径
        public int _radius = 5;

        //是否允许窗体改变大小
        public bool _canResize = true;

        public Image _fringe = (Bitmap)Image.FromFile(@".\Res\fringe_bkg.png");
        public Image _formBkg = (Bitmap)Image.FromFile(@".\Res\FormBkg\4-1.jpg");

        //系统按钮管理器
        public SystemButtonManager _systemButtonManager;

        #endregion
        
        #region 属性

        [DefaultValue(typeof(byte), "5")]
        public int Radius
        {
            get
            {
                return _radius;
            }
            set
            {
                if (_radius != value)
                {
                    _radius = value;
                    this.Invalidate();
                }
            }
        }

        public bool CanResize
        {
            get
            {
                return _canResize;
            }
            set
            {
                if (_canResize != value)
                {
                    _canResize = value;
                }
            }
        }

        public override Image BackgroundImage
        {
            get
            {
                return _formBkg;
            }
            set
            {
                if (_formBkg != value)
                {
                    _formBkg = value;
                    Invalidate();
                }
            }
        }

        internal Rectangle IconRect
        {
            get
            {
                if (base.ShowIcon && base.Icon != null)
                {
                    return new Rectangle(8, 6, SystemInformation.SmallIconSize.Width, SystemInformation.SmallIconSize.Width);
                }
                return Rectangle.Empty;
            }
        }

        internal Rectangle TextRect
        {
            get
            {
                if (base.Text.Length != 0)
                {
                    return new Rectangle(IconRect.Right + 2, 4, Width - (8 + IconRect.Width + 2), Font.Height);
                }
                return Rectangle.Empty;
            }
        }

        internal SystemButtonManager SystemButtonManager
        {
            get
            {
                if (_systemButtonManager == null)
                {
                    _systemButtonManager = new SystemButtonManager(this);
                }
                return _systemButtonManager;
            }
        }

        #endregion

        #region 重载

        protected override CreateParams CreateParams
        {
            get
            {
                CreateParams cp = base.CreateParams;
                if (!DesignMode)
                {
                    if (MaximizeBox) { cp.Style |= (int)WindowStyle.WS_MAXIMIZEBOX; }
                    if (MinimizeBox) { cp.Style |= (int)WindowStyle.WS_MINIMIZEBOX; }
                    //cp.ExStyle |= (int)WindowStyle.WS_CLIPCHILDREN;  //防止因窗体控件太多出现闪烁
                    cp.ClassStyle |= (int)ClassStyle.CS_DropSHADOW;  //实现窗体边框阴影效果
                }
                return cp;
            }
        }

        protected override void OnCreateControl()
        {
            base.OnCreateControl();
            RenderHelper.SetFormRoundRectRgn(this, Radius);
        }

        protected override void OnSizeChanged(EventArgs e)
        {
            base.OnSizeChanged(e);
            RenderHelper.SetFormRoundRectRgn(this, Radius);
            UpdateSystemButtonRect();
            UpdateMaxButton();
        }

        protected override void WndProc(ref Message m)
        {
            switch (m.Msg)
            {
                case Win32.WM_ERASEBKGND:
                    m.Result = IntPtr.Zero;
                    break;
                case Win32.WM_NCHITTEST:
                    WmNcHitTest(ref m);
                    break;
                default:
                    base.WndProc(ref m);
                    break;
            }
        }

        protected override void OnMouseMove(MouseEventArgs e)
        {
            base.OnMouseMove(e);
            SystemButtonManager.ProcessMouseOperate(e.Location, MouseOperate.Move);
        }

        protected override void OnMouseDown(MouseEventArgs e)
        {
            base.OnMouseDown(e);
            if (e.Button == MouseButtons.Left)
            {
                SystemButtonManager.ProcessMouseOperate(e.Location, MouseOperate.Down);
            }
        }

        protected override void OnMouseUp(MouseEventArgs e)
        {
            base.OnMouseUp(e);
            if (e.Button == MouseButtons.Left)
            {
                SystemButtonManager.ProcessMouseOperate(e.Location, MouseOperate.Up);
            }
        }

        protected override void OnMouseLeave(EventArgs e)
        {
            base.OnMouseLeave(e);
            SystemButtonManager.ProcessMouseOperate(Point.Empty, MouseOperate.Leave);
        }

        protected override void OnPaint(PaintEventArgs e)
        {
            base.OnPaint(e);

            e.Graphics.SmoothingMode = SmoothingMode.AntiAlias;
            e.Graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;

            //draw BackgroundImage
            e.Graphics.DrawImage(_formBkg, ClientRectangle, new Rectangle(0, 0, _formBkg.Width, _formBkg.Height), GraphicsUnit.Pixel);

            //draw form main part
            RenderHelper.DrawFromAlphaMainPart(this, e.Graphics);

            //draw system buttons
            SystemButtonManager.DrawSystemButtons(e.Graphics);

            //draw fringe
            RenderHelper.DrawFormFringe(this, e.Graphics, _fringe, Radius);

            //draw icon
            if (Icon != null && ShowIcon)
            {
                e.Graphics.DrawIcon(Icon, IconRect);
            }

            //draw text
            if (Text.Length != 0)
            {
                TextRenderer.DrawText(
                    e.Graphics,
                    Text, Font,
                    TextRect,
                    Color.White,
                    TextFormatFlags.SingleLine | TextFormatFlags.EndEllipsis);
            }



        }



        #endregion

        #region 私有方法


        public void FormExIni()
        {
            this.MaximumSize = Screen.PrimaryScreen.WorkingArea.Size;

            SetStyles();
        }

        public void SetStyles()
        {
            SetStyle(ControlStyles.UserPaint, true);
            SetStyle(ControlStyles.AllPaintingInWmPaint, true);
            SetStyle(ControlStyles.OptimizedDoubleBuffer, true);
            SetStyle(ControlStyles.ResizeRedraw, true);
            SetStyle(ControlStyles.SupportsTransparentBackColor, true);
            UpdateStyles();
        }

        public void WmNcHitTest(ref Message m)  //调整窗体大小
        {
            int wparam = m.LParam.ToInt32();
            Point mouseLocation = new Point(RenderHelper.LOWORD(wparam), RenderHelper.HIWORD(wparam));
            mouseLocation = PointToClient(mouseLocation);

            if (WindowState != FormWindowState.Maximized)
            {
                if (CanResize == true)
                {
                    if (mouseLocation.X < 5 && mouseLocation.Y < 5)
                    {
                        m.Result = new IntPtr(Win32.HTTOPLEFT);
                        return;
                    }

                    if (mouseLocation.X > Width - 5 && mouseLocation.Y < 5)
                    {
                        m.Result = new IntPtr(Win32.HTTOPRIGHT);
                        return;
                    }

                    if (mouseLocation.X < 5 && mouseLocation.Y > Height - 5)
                    {
                        m.Result = new IntPtr(Win32.HTBOTTOMLEFT);
                        return;
                    }

                    if (mouseLocation.X > Width - 5 && mouseLocation.Y > Height - 5)
                    {
                        m.Result = new IntPtr(Win32.HTBOTTOMRIGHT);
                        return;
                    }

                    if (mouseLocation.Y < 3)
                    {
                        m.Result = new IntPtr(Win32.HTTOP);
                        return;
                    }

                    if (mouseLocation.Y > Height - 3)
                    {
                        m.Result = new IntPtr(Win32.HTBOTTOM);
                        return;
                    }

                    if (mouseLocation.X < 3)
                    {
                        m.Result = new IntPtr(Win32.HTLEFT);
                        return;
                    }

                    if (mouseLocation.X > Width - 3)
                    {
                        m.Result = new IntPtr(Win32.HTRIGHT);
                        return;
                    }
                }
            }
            m.Result = new IntPtr(Win32.HTCLIENT);
        }

        public void UpdateMaxButton()  //根据窗体的状态更换最大(还原)系统按钮
        {
            bool isMax = WindowState == FormWindowState.Maximized;
            if (isMax)
            {
                SystemButtonManager.SystemButtonArray[1].NormalImg = Image.FromFile(@".\Res\SystemButton\restore_normal.png");
                SystemButtonManager.SystemButtonArray[1].HighLightImg = Image.FromFile(@".\Res\SystemButton\restore_highlight.png");
                SystemButtonManager.SystemButtonArray[1].PressedImg = Image.FromFile(@".\Res\SystemButton\restore_press.png");
                SystemButtonManager.SystemButtonArray[1].ToolTip = "还原";
            }
            else
            {
                SystemButtonManager.SystemButtonArray[1].NormalImg = Image.FromFile(@".\Res\SystemButton\max_normal.png");
                SystemButtonManager.SystemButtonArray[1].HighLightImg = Image.FromFile(@".\Res\SystemButton\max_highlight.png");
                SystemButtonManager.SystemButtonArray[1].PressedImg = Image.FromFile(@".\Res\SystemButton\max_press.png");
                SystemButtonManager.SystemButtonArray[1].ToolTip = "最大化";
            }
        }

        protected void UpdateSystemButtonRect()
        {
            bool isShowMaxButton = MaximizeBox;
            bool isShowMinButton = MinimizeBox;
            Rectangle closeRect = new Rectangle(
                    Width - SystemButtonManager.SystemButtonArray[0].NormalImg.Width,
                    -1,
                    SystemButtonManager.SystemButtonArray[0].NormalImg.Width,
                    SystemButtonManager.SystemButtonArray[0].NormalImg.Height);

            //update close button location rect.
            SystemButtonManager.SystemButtonArray[0].LocationRect = closeRect;

            //Max
            if (isShowMaxButton)
            {
                SystemButtonManager.SystemButtonArray[1].LocationRect = new Rectangle(
                    closeRect.X - SystemButtonManager.SystemButtonArray[1].NormalImg.Width,
                    -1,
                    SystemButtonManager.SystemButtonArray[1].NormalImg.Width,
                    SystemButtonManager.SystemButtonArray[1].NormalImg.Height);
            }
            else
            {
                SystemButtonManager.SystemButtonArray[1].LocationRect = Rectangle.Empty;
            }

            //Min
            if (!isShowMinButton)
            {
                SystemButtonManager.SystemButtonArray[2].LocationRect = Rectangle.Empty;
                return;
            }
            if (isShowMaxButton)
            {
                SystemButtonManager.SystemButtonArray[2].LocationRect = new Rectangle(
                    SystemButtonManager.SystemButtonArray[1].LocationRect.X - SystemButtonManager.SystemButtonArray[2].NormalImg.Width,
                    -1,
                    SystemButtonManager.SystemButtonArray[2].NormalImg.Width,
                    SystemButtonManager.SystemButtonArray[2].NormalImg.Height);
            }
            else
            {
                SystemButtonManager.SystemButtonArray[2].LocationRect = new Rectangle(
                   closeRect.X - SystemButtonManager.SystemButtonArray[2].NormalImg.Width,
                   -1,
                   SystemButtonManager.SystemButtonArray[2].NormalImg.Width,
                   SystemButtonManager.SystemButtonArray[2].NormalImg.Height);
            }
        }

        #endregion

        #endregion

        BLL.TCPComm b_TCPComm = new BLL.TCPComm();
        string temp, hum, ill, soilHum, rain, area, facilitiesNo;        //设置收到的数据为变量，自动模式方便判断
        string head, end;                                                //定义头码和尾码
        string modeId;
        int areaAuto, areaAutoMode, tempMin, tempMax, illMin, illMax, soilHumMin, soilHumMax;  //自动控制模式设置的范围值及控制区域        
        
        private serialPort myserialPort = new serialPort();              //实例化一个串口对象
        private Display mydisplay = new Display();                       //实例化一个点阵屏显示数据的对象
        private dataDeal mydataDeal = new dataDeal();                    //实例化一个数据处理对象 
        private autoMode myAutoMode = new autoMode();                    //实例化手机网页端自动处理对象
        
        private Thread autoModeThr = null;                               //手机端、网页自动化控制线程
        private Thread updateData = null;                                //当串口有数据发送时，实时刷新页面温度等数据 
        private Thread chkMacState = null;                               //查看各个机械设备风机、加热灯等开启状况
        private Thread sendeOrderThr = null;                             //发送串口发送指令线程
        private Thread manChkDataThr = null;                             //手动模式检测新指令线程
        private Thread _showData;                                        //多线程显示屏处理       

        public static Thread chkThread;     //判断接受数据是否为新的 线程
        BLL.recDataDeal b_recDataDeal = new BLL.recDataDeal();
        #region 判断接受数据是否为新的 若为新则进行数据处理
        public void dataRecPro()
        {
            string temp1 = b_recDataDeal.macActionMsg;
            
            while (true)
            {
                //if (temp1 != richTextBoxFacState.Text && !String.IsNullOrEmpty(richTextBoxFacState.Text))
                //{
                    richTextBoxFacState.Text += b_TCPComm.dataRec;
                    temp1 = b_recDataDeal.macActionMsg;
                //}
            }

        }
        #endregion

        //public Form1()
        //{
        //    FormExIni();
        //    _systemButtonManager = new SystemButtonManager(this);
        //    InitializeComponent();
        //}

        //窗口载入事件
        //调用myserialPort类的LoadSerialPortConfiguration方法  
        //在对象串口下拉框添加串口名称项，波特率选项默认为1152000方法
        private void Form1_Load(object sender, EventArgs e)
        {
            System.Windows.Forms.Control.CheckForIllegalCrossThreadCalls = false;       //允许在线程中直接改变控件属性如果捕获了对错误线程的调用，则为 true；否则为 false。

            autoModeThr = new Thread(new ThreadStart(myAutoMode.chkMode));              //实例化是手机端、网页自动化控制线程
            autoModeThr.Start();                                                        //开启线程

            sendeOrderThr = new Thread(new ThreadStart(comSendOrder));
            sendeOrderThr.Start();
         
            manChkDataThr = new Thread(new ThreadStart(manModeThr));
            manChkDataThr.Start();

            _showData = new Thread(screenShow);                                         //点阵屏刷新函数
            _showData.Start();  

            mydataDeal.modeNameAdd(comboBoxModeName);                                   //模式名称动态添加下拉

            //窗体载入时，各个按钮状况
            ButtonEnableOrVisable("Form_Load");

            comboBoxDefault.SelectedIndex = 0;

            chkThread = new Thread(new ThreadStart(dataRecPro));    //判断接受数据是否为新的 线程
            chkThread.Start();
        }
        
        #region 点阵屏生成显示图片函数(无限循环)
        public void screenShow()
        {
            while (true)
            {
                //引用display类的方法更新图片，显示数据
                mydisplay.updateImage();
            }
        } 
        #endregion

        //打开串口事件 
        //禁用相关按钮与下拉框
        private void butOpenCom_Click(object sender, EventArgs e)
        {
            //打开wifi通讯
            if (butOpenCom.Text == "开启通讯")
            {
                try
                {
                    
                    //b_TCPComm.sendData("text");
                    //b_TCPComm.openComm(textBoxSerIP.Text.Trim().ToString(),textBoxPort.Text.Trim());
                    b_TCPComm.openComm("192.168.250.1","8002");
                    //在此处调用按钮函数
                    ButtonEnableOrVisable("开启通讯");
                    butOpenCom.Text = "关闭通讯";
                    textBoxSerIP.ReadOnly = true;
                    textBoxPort.ReadOnly = true;
                }
                catch (Exception ex)
                {
                    MessageBox.Show("wifi通讯无法打开，错误：" + ex.ToString());
                }
            }
            //关闭 wifi 通讯
            else
            {
                b_TCPComm.closeSocket();
                ButtonEnableOrVisable("关闭通讯");
                butOpenCom.Text = "开启通讯";
                textBoxSerIP.ReadOnly = false;
                textBoxPort.ReadOnly = false;
            }
        }

        #region 数据截取方法。截取完成，调用mydataDeal.insertDb(sqlComm);方法将数据插入数据库
        private bool dataDeal(string data)
        {
            if (data.Length == 9 || data.Length == 7)
            {
                string onlineArea = data.Substring(1, 2);
                string onlineSensor = data.Substring(4, 2);
                string msg = "";
                string onlineOrOff = int.Parse(data.Substring(6, 1)) == 0 ? "掉线" : "上线";
                if (data.Contains("C"))
                {
                    msg = DateTime.Now.ToString()+ "   区域：" + onlineArea + " 传感器节点：" + onlineSensor + "  " + onlineOrOff;
                }

                if (data.Contains("F"))
                {
                    msg = DateTime.Now.ToString() + "   区域：" + onlineArea + "   控制节点：" + onlineSensor + "  " + onlineOrOff;
                }

                richTextBoxFacState.Text += msg+"\n";
                this.richTextBoxFacState.SelectionStart = this.richTextBoxFacState.TextLength;
                this.richTextBoxFacState.ScrollToCaret();
            }

            end = data.Substring(23, 2);                         //尾码
            head = data.Substring(data.IndexOf("A"), 2);         //头码
            //data.Substring(1, 1) != "Y" 下位机操作成功后返回 Y11 第二位为设备号(风扇、水泵等)
            //反馈机制尚未完善，所以先屏蔽这个返回指令
            if (head != "AA" && end != "55" && data.Substring(1, 1) != "Y")
            {
                MessageBox.Show("数据接收不完整!");
                return false;
            }
            //接受的数据指令插入数据库
            string sqlComm = "INSERT INTO orderReceive(orderReceive,receTime) VALUES('" + data + "',getdate())";
            //MessageBox.Show(sqlComm);
            mydataDeal.insertDb(sqlComm);

            //截取数据插入数据库
            sqlComm = "INSERT INTO dealReceive (modeId,area,facilitiesNo,temperature,humidity,illumination,soilHum,rain,receiveTime)";
            string value = "VALUES(";

            area = data.Substring(3, 2);                                               //区域号
            facilitiesNo = data.Substring(data.IndexOf("C") + 1, 2);                   //设备号
            temp = data.Substring(data.IndexOf("T") + 1, 2);                           //温度
            hum = data.Substring(data.IndexOf("H") + 1, 2);                            //湿度
            ill = data.Substring(data.IndexOf("I") + 1, 3);                            //光照
            soilHum = data.Substring(data.IndexOf("S") + 1, 2);                        //土壤湿度
            //soilHum = (100 - int.Parse(soilHum)).ToString();
            rain = data.Substring(data.IndexOf("R") + 1, 1);
            value += modeId.ToString() + "," + area + "," + facilitiesNo + "," + temp + "," + hum + "," + ill + "," + soilHum + "," + rain + ",";
            value += ConvertDateTimeInt(DateTime.Now) + ")";
            sqlComm += value;
            //MessageBox.Show(sqlComm);
            mydataDeal.insertDb(sqlComm);           //mydataDeal.insertDb 方法:将数据插入数据库        

            //判断区域号是否存在，若不存在则在设备表插入
            mydataDeal.insertArea(modeId.ToString(), area, facilitiesNo);
            return true;
        } 
        #endregion


        //自动模式按钮点击事件
        //禁用范围值文本框
        //调用OpenAutoMode() 方法将范围值插入数据库
        public void butAutoModel_Click(object sender, EventArgs e)
        {
            if (butAutoModel.Text == "开启自动模式")
            {
                int areaAutoMode;
                try
                {
                    areaAutoMode = int.Parse(comboBoxAutoModeArea.Text);
                    //判断输入是否正确，并把范围设定值插入数据库
                    if (JudgeAutoModeValue())
                    {
                        //MessageBox.Show(areaAutoMode.ToString());
                        string sql = "INSERT INTO actionInstruction(modeId,orderFrom,area,orderSend,instruction,actionTime) VALUES ('" + modeId + "','PC'," + areaAutoMode + ",'PCAUTO1','客户端开启自动模式',getdate())";
                        //MessageBox.Show(sql);
                        mydataDeal.insertDb(sql);
                        ButtonEnableOrVisable("开启自动模式");
                                  
                        butAutoModel.Text = "关闭自动模式";
                    }
                }
                catch(Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                    return;
                }
            }
            //关闭自动模式
            else
            {
                
                butAutoModel.Text = "开启自动模式";
                string sql = "INSERT INTO actionInstruction(modeId,orderFrom,area,orderSend,instruction,actionTime) VALUES ('" + modeId + "','PC'," + areaAutoMode + ",'PCAUTO0','客户端关闭自动模式',getdate())";
                mydataDeal.insertDb(sql);
                ButtonEnableOrVisable("关闭自动模式");
            }
            closeOpenFac();
        }

        //关闭模式时， 关闭对应区域的所有设备
        public void closeOpenFac()
        {
            //先关闭线程，关闭指令发送后
            //在开启线程
            autoModeThr.Abort();
            area = comboBoxAutoModeArea.Text;
            string[] openFac = mydataDeal.queryOpenFac(modeId, comboBoxAutoModeArea.Text);
            string facNo;
            for (int i = 0; i < openFac.Length; i++)
            {
                facNo = openFac[i].Substring(0, 2);
                //MessageBox.Show(facNo.ToString());
                mydataDeal.updateDb("0", modeId, area, facNo);
                //MessageBox.Show(facNo.ToString());
                b_TCPComm.sendData("AAE0" + comboBoxAutoModeArea.Text.ToString() + "F01" + facNo + "055");
                Thread.Sleep(1500);
            }
            autoModeThr = new Thread(new ThreadStart(myAutoMode.chkMode));              //实例化是手机端、网页、桌面版自动化控制线程
            autoModeThr.Start();
        }
        //判断输入的值是否正确并范围值插入数据库
        private bool JudgeAutoModeValue()
        {
            int[] valueSize = mydataDeal.chkModeSensor(modeId);
            int temp;
            modeId = mydataDeal.modeNameToModeId(comboBoxModeName.Text);
            areaAuto = int.Parse(comboBoxAutoModeArea.Text);

            bool tempFlag = false, illFlag = false, soilHumFlag = false;
           
            for (int i = 0; i < valueSize.Length; i++)
            {
                temp = valueSize[i];
                //温度输入值判断
                if (temp == 1)
                {
                    if (JudgeAll(tempMin, tempMax, "temp", textBoxTempMin, textBoxTempMax))
                    {
                        tempFlag = true;
                    }
                    else
                    {
                        return false;
                    }                    
                }

                //光照强度输入判断
                if (temp == 3)
                {
                    if (JudgeAll(illMin, illMax, "ill", textBoxIllMin, textBoxIllMax))
                    {
                        illFlag = true;
                    }
                    else
                    {
                        return false;
                    }
                }

                //土壤湿度输入值判断
                if (temp == 4)
                {
                    if (JudgeAll(soilHumMin, soilHumMax, "soilHum", textBoxSoilHumMin, textBoxSoilHumMax))
                    {
                        soilHumFlag = true;
                    }
                    else
                    {
                        return false;
                    }
                }
            }

            if (valueSize.Length == 1 && tempFlag)
            {
                return true;
            }
            if (valueSize.Length == 3 && tempFlag && illFlag && soilHumFlag)
            {
                return true;
            }
                
            string sql = "INSERT INTO autoModeValue(modeId,area,tempMin,tempMax,illMin,illMax,soilHumMin,soilHumMax,setTime)VALUES('" + modeId + "','" + areaAuto + "','" + tempMin + "','" + tempMax + "','" + illMin + "','" + illMax + "','" + soilHumMin + "','" + soilHumMax + "',getdate())";
            //MessageBox.Show(sql);
            mydataDeal.insertDb(sql);
            return true;
        }

        #region 服务器端验证输入数据是否合法
        //判断归总
        private bool JudgeAll(int minValue, int maxValue, string type, TextBox textBoxMin, TextBox textBoxMax)
        {
            //判断输入值是否为空
            if (JudegValueNull(textBoxMin, textBoxMax))
            {
                minValue = int.Parse(textBoxMin.Text);
                maxValue = int.Parse(textBoxMax.Text);

                if (type == "temp")
                {
                    tempMin = minValue;
                    tempMax = maxValue;
                }
                if (type == "ill")
                {
                    illMin = minValue;
                    illMax = maxValue;
                }
                if (type == "soilHum")
                {
                    soilHumMin = minValue;
                    soilHumMax = maxValue;
                }
                //判断输入范围值是否合理 && 判断输入值输入是否为整数
                if (JudgeValueRang(minValue, maxValue, type) && JudegValueInt(textBoxMin, textBoxMax, minValue, maxValue))
                {
                    return true;
                }
                return false;
            }
            return false;
        }

        //判断最大值>最小值
        private bool JudgeValueRang(int minValue, int maxValue, string type)
        {
            string msg = "";
            switch (type)
            {
                case "temp": msg = "温度数据有错，必须为正整数，且 范围1<范围2"; break;
                case "soilHum": msg = "土壤湿度数据有错，必须为正整数，且 范围1<范围2"; break;
                case "ill": msg = "光照数据有错，必须为正整数，且 范围1<范围2"; break;
            }
            //验证自动控制输入值
            if (minValue > maxValue || minValue < 0 || maxValue < 0)
            {
                MessageBox.Show(msg);
                return false;
            }
            return true;
        }

        //判断文本框输入为空
        private bool JudegValueNull(TextBox textBoxMin, TextBox textBoxMax)
        {
            if (textBoxMin.Text == "" || textBoxMax.Text == "")
            {
                MessageBox.Show("自动模式下设定值不能为空");
                return false;
            }
            return true;
        }

        //判断文本框输入是否为整数
        private bool JudegValueInt(TextBox textBoxMin, TextBox textBoxMax, int minValue, int maxValue)
        {
            if (int.TryParse(textBoxMin.Text, out minValue) == false || int.TryParse(textBoxMax.Text, out maxValue) == false)
            {
                MessageBox.Show("请检查输入，范围值请输入整数！");
                return false;
            }
            return true;
        }        
        #endregion

        #region 自动模式：判断指令是否为新的指令(与前一个生成的指令比较)
        string orderBefore;
        public void comSendOrder()
        {
            while (true)
            {
                try
                {
                    string newOrder = serialPort.toControllerNew();
                    if (newOrder != orderBefore && newOrder != null)
                    {
                        b_TCPComm.sendData(newOrder);
                        orderBefore = newOrder;
                    }
                }
                catch
                {
                    ;
                }
            }
        } 
        #endregion


        #region 手动模式扫描是否为新的指令manModeThr(),(无限循环)
        public void manModeThr()
        {
            string pcCompareBefore, webCompareBefore, appCompareBefore;
            string pcOrder, webOrder, appOrder;

            pcCompareBefore = mydataDeal.manFromSendOrder("PC");
            webCompareBefore = mydataDeal.manFromSendOrder("WEB");
            appCompareBefore = appOrder = mydataDeal.manFromSendOrder("APP");
            while (true)
            {
                try
                {
                    //扫描数据库是否有新的 手动指令插入数据库，若为新则发送。否则不发
                    pcOrder = mydataDeal.manFromSendOrder("PC");
                    if (pcOrder != pcCompareBefore)
                    {
                        b_TCPComm.sendData(pcOrder);
                        pcCompareBefore = pcOrder;
                    }

                    webOrder = mydataDeal.manFromSendOrder("WEB");
                    if (webOrder != webCompareBefore)
                    {
                        b_TCPComm.sendData(webOrder);
                        webCompareBefore = webOrder;
                    }

                    appOrder = mydataDeal.manFromSendOrder("APP");
                    if (appOrder != appCompareBefore)
                    {
                        b_TCPComm.sendData(appOrder);
                        appCompareBefore = appOrder;
                    }

                }
                catch
                {
                    ;
                }
            }
        } 
        #endregion
        
        #region 查询最新数据函数ShowData()(无限循环)
        public void ShowData()
        {
            while (true)
            {
                try
                {
                    int[] nowData = mydataDeal.selectData(modeId, areaAuto);
                    labelNowTemp.Text = nowData[0].ToString() + " ℃";
                    labelNowHum.Text = nowData[1].ToString() + " %";
                    labelNowIll.Text = nowData[2].ToString() + " KLUX";
                    if (nowData[3] == 0)
                    {
                        labelNowRain.Text = "晴天";
                    }
                    else
                    {
                        labelNowRain.Text = "雨天";
                    }
                    labelNowSoilHum.Text = nowData[4].ToString() + " %";
                    labelTime.Text = GetNoralTime(nowData[6].ToString()).ToString().Trim();
                    labelModeName.Text = comboBoxModeName.Text.ToString().Trim();
                    nowData = null;

                    //判断对应区域控制状态
                    labelAreaState.Text = mydataDeal.JudgeAreaAutoMode(int.Parse(comboBoxAutoModeArea.Text), modeId);

                    //判断该区域是否已被   手机端或者网页端  开启自动模式
                    if (labelAreaState.Text.Contains("模式") && !labelAreaState.Text.Contains("客户端"))
                    {
                        try
                        {
                            butAutoModel.Enabled = false;
                            butManModel.Enabled = false;
                            string side = labelAreaState.Text.Substring(0, 3);
                            if (labelAreaState.Text.Contains("自动"))
                            {
                                //查询区域最新设定范围值
                                groupBoxSetValue.Text = "自动控制范围值设置-" + side;
                                //在文本框显示设定范围值
                                int[] autoValue = mydataDeal.selectAutoValue(modeId.ToString(), areaAuto);
                                textBoxTempMin.Text = autoValue[0].ToString();
                                textBoxTempMax.Text = autoValue[1].ToString();
                                textBoxIllMin.Text = autoValue[2].ToString();
                                textBoxIllMax.Text = autoValue[3].ToString();
                                textBoxSoilHumMin.Text = autoValue[4].ToString();
                                textBoxSoilHumMax.Text = autoValue[5].ToString();
                            }
                        }
                        catch
                        {
                        }

                    }

                    if (labelAreaState.Text.Contains("客户端开启手动模式"))
                    {
                        butAutoModel.Enabled = false;
                        //Thread.Sleep(500);
                        butManModel.Text = "关闭手动模式";
                    }

                    if (labelAreaState.Text.Contains("客户端开启自动模式"))
                    {
                        butManModel.Enabled = false;
                        butAutoModel.Text = "关闭自动模式";
                    }

                    if (labelAreaState.Text == "-" && butAutoModel.Text == "关闭通讯")
                    {
                        groupBoxSetValue.Text = "自动控制范围值设置";
                        butAutoModel.Enabled = true;
                        butManModel.Enabled = true;
                        butManModel.Text = "开启手动模式";
                        butAutoModel.Text = "开启自动模式";
                    }
                }
                catch 
                {
                }
            }
        } 
        #endregion

        //刷新区域号按钮函数
        private void butFlashArea_Click(object sender, EventArgs e)
        {
            try
            {
                comboBoxAutoModeArea.Items.Clear();
                //MessageBox.Show(comboBoxModeId.Text);
                mydataDeal.selectArea(modeId, comboBoxAutoModeArea);                                //区域号下拉框动态添加下拉选项
                //comboBoxAutoModeArea.SelectedIndex = 0;
            }
            catch
            {
                MessageBox.Show("未搜索到区域设备");
            }
        }

        #region 开启/关闭手动模式按钮事件
        private void butManModel_Click(object sender, EventArgs e)
        {
            int areaManMode;
            string instruction;
            string control;
            try
            {
                areaManMode = int.Parse(comboBoxAutoModeArea.Text);
            }
            catch
            {
                MessageBox.Show("请选择区域号在选择模式！");
                return;
            }
            if (butManModel.Text == "开启手动模式")
            {
                instruction = "客户端开启手动模式";
                control = "PCMAN1";
                ButtonEnableOrVisable("开启手动模式");
                butManModel.Text = "关闭手动模式";

            }
            else   //关闭手动模式
            {
                instruction = "客户端关闭手动模式";
                ButtonEnableOrVisable("关闭手动模式");
                control = "PCMAN0";
                butManModel.Text = "开启手动模式";
                //关闭所有设备
                closeOpenFac();

            }
            //手动模式操作，插入数据库
            string sql = "INSERT INTO actionInstruction(modeId,orderFrom,area,mode,orderSend,instruction,actionTime) VALUES ('" + modeId + "','PC'," + areaManMode + ",'MAN','" + control + "','" + instruction + "',getdate())";
            mydataDeal.insertDb(sql);
        } 
        #endregion

        //控制区域区域下拉框区域值改变时
        //开启/关闭更新数据线程
        private void comboBoxAutoModeArea_SelectedIndexChanged(object sender, EventArgs e)
        {
            chkMacState = new Thread(new ThreadStart(chkFacState));
            areaAuto = int.Parse(comboBoxAutoModeArea.Text);
            labelQueryArea.Text = comboBoxAutoModeArea.Text;

            //ShowData函数 更新对应模式下对应区域采集的数据
            updateData = new Thread(new ThreadStart(ShowData));
            
            //当开启通讯后，更新数据线程开启
            if (butOpenCom.Text == "关闭通讯")
            {
                updateData.Start();
                chkMacState.Start();
            }
            //当关闭通讯后，更新数据线程关闭
            else
            {
                updateData.Abort();
                chkMacState.Abort();
            }
        }


        #region 检查各设备开启状况chkFacState() (无限循环)
        public void chkFacState()
        {
            while (true)
            {
                try
                {
                    string[] machime = new string[5];
                    areaAutoMode = int.Parse(comboBoxAutoModeArea.Text);                           //控制区域号
                    machime = mydataDeal.chkFacState(modeId.ToString(), areaAutoMode);             //检查各个设备的状态，返回文本“开/关”
                    labelFanState.Text = machime[0];
                    labelHotLigState.Text = machime[1];
                    labelPumpState.Text = machime[2];
                    labelWinState.Text = machime[3];
                    labelLightState.Text = machime[4];

                    butFanSwitch.Text = ManModeButState(labelFanState.Text);
                    butWinSwitch.Text = ManModeButState(labelWinState.Text);
                    butHotLigSwitch.Text = ManModeButState(labelHotLigState.Text);
                    butLightSwitch.Text = ManModeButState(labelLightState.Text);
                    butPumpSwitch.Text = ManModeButState(labelPumpState.Text);
                    if (butOpenCom.Text == "开启通讯")
                    {
                        ButtonEnableOrVisable("开启通讯");
                    }
                }
                catch
                {
                    ;
                }
            }
        } 
        #endregion
        private string ManModeButState(string facNowState)
        {
            string butState = "";
            if (facNowState == "关")
            {
                butState = "开";
            }
            if (facNowState == "开")
            {
                butState = "关";
            }
            return butState;
        }

        #region 各个设备操作按钮开关事件
        //风机开关
        private void butFanSwitch_Click(object sender, EventArgs e)
        {
            //butFanSwitch.Enabled = false;
            area = comboBoxAutoModeArea.Text;
            if (butFanSwitch.Text == "开")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M11", "开启风机", "1");
                butFanSwitch.Text = "关";
                mydataDeal.updateDb("1", modeId, area, "M1");
                return;
            }
            if (butFanSwitch.Text == "关")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M10", "关闭风机", "1");
                butFanSwitch.Text = "开";
                mydataDeal.updateDb("0", modeId, area, "M1");
                return;
            }
        }

        //天窗开关
        private void butWinSwitch_Click(object sender, EventArgs e)
        {
            //butWinSwitch.Enabled = false;
            area = comboBoxAutoModeArea.Text;
            if (butWinSwitch.Text == "开")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M41", "开启天窗", "1");
                butWinSwitch.Text = "关";
                mydataDeal.updateDb("1", modeId, area, "M4");
                return;
            }
            if (butWinSwitch.Text == "关")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M40", "关闭天窗", "1");
                butWinSwitch.Text = "开";
                mydataDeal.updateDb("0", modeId, area, "M4");
                return;
            }
        }

        //加热灯开关
        private void butHotLigSwitch_Click(object sender, EventArgs e)
        {
            //butHotLigSwitch.Enabled = false;
            area = comboBoxAutoModeArea.Text;
            if (butHotLigSwitch.Text == "开")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M21", "开启加热灯", "1");
                butHotLigSwitch.Text = "关";
                mydataDeal.updateDb("1", modeId, area, "M2");
                return;
            }
            if (butHotLigSwitch.Text == "关")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M20", "关闭加热灯", "1");
                butHotLigSwitch.Text = "开";
                mydataDeal.updateDb("0", modeId, area, "M2");
                return;
            }
        }

        //白炽灯开关
        private void butLightSwitch_Click(object sender, EventArgs e)
        {
            //butLightSwitch.Enabled = false;
            area = comboBoxAutoModeArea.Text;
            if (butLightSwitch.Text == "开")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M51", "开启白炽灯", "1");
                butLightSwitch.Text = "关";
                mydataDeal.updateDb("1", modeId, area, "M5");
                return;
            }
            else if (butLightSwitch.Text == "关")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M50", "关闭白炽灯", "1");
                butLightSwitch.Text = "开";
                mydataDeal.updateDb("0", modeId, area, "M5");
                return;
            }
        }

        //水泵开关
        private void butPumpSwitch_Click(object sender, EventArgs e)
        {
            //butPumpSwitch.Enabled = false;
            area = comboBoxAutoModeArea.Text;
            if (butPumpSwitch.Text == "开")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M31", "开启水泵", "1");
                butPumpSwitch.Text = "关";
                mydataDeal.updateDb("1", modeId, area, "M3");
                return;
            }
            else if (butPumpSwitch.Text == "关")
            {
                myserialPort.manSendOrder(modeId, "PC", area, "M30", "关闭水泵", "1");
                butPumpSwitch.Text = "开";
                mydataDeal.updateDb("0", modeId, area, "M3");
                return;
            }
        } 
        #endregion

        //窗体关闭时，关闭所有控件、线程
        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
        {
            if (butAutoModel.Text == "关自动模式" || butManModel.Text == "关闭手动模式")
            {
                string sql = "INSERT INTO actionInstruction(modeId,orderFrom,area,orderSend,instruction,actionTime) VALUES ('" + modeId + "','PC'," + areaAutoMode + ",'PCAUTO0','客户端关闭自动模式',getdate())";
                mydataDeal.insertDb(sql);
            }
            System.Environment.Exit(0);
        }
        
        /// 时间戳转为C#格式时间
        private DateTime GetNoralTime(string now)
        {
            string timeStamp = now;
            DateTime dtStart = TimeZone.CurrentTimeZone.ToLocalTime(new DateTime(1970, 1, 1));
            long lTime = long.Parse(timeStamp + "0000000");
            TimeSpan toNow = new TimeSpan(lTime);
            DateTime dtResult = dtStart.Add(toNow);
            return dtResult;
        }

        /// DateTime时间格式转换为Unix时间戳格式
        public int ConvertDateTimeInt(System.DateTime time)
        {
            System.DateTime startTime = TimeZone.CurrentTimeZone.ToLocalTime(new System.DateTime(1970, 1, 1));
            return (int)(time - startTime).TotalSeconds;
        }

        //以下五个方法为：点击手动各设备开关按钮后，按钮不能立刻操作。
        //待设备状态改变后，按钮才能操作
        private void labelFanState_TextChanged(object sender, EventArgs e)
        {
            //if(labelFanState.Text != "-" && butManModel.Text == "关闭手动模式")
            //    butFanSwitch.Enabled = true;            
        }

        private void labelWinState_TextChanged(object sender, EventArgs e)
        {
            //if (labelWinState.Text != "-" && butManModel.Text == "关闭手动模式")
            //    butWinSwitch.Enabled = true;
        }

        private void labelHotLigState_TextChanged(object sender, EventArgs e)
        {
            //if (labelHotLigState.Text != "-" && butManModel.Text == "关闭手动模式")
            //    butHotLigSwitch.Enabled = true;
        }

        private void labelLightState_TextChanged(object sender, EventArgs e)
        {
            //if (labelLightState.Text != "-" && butManModel.Text == "关闭手动模式")
            //    butLightSwitch.Enabled = true;
        }

        private void labelPumpState_TextChanged(object sender, EventArgs e)
        {
            //if (labelPumpState.Text != "-" && butManModel.Text == "关闭手动模式")
            //    butPumpSwitch.Enabled = true;
        }
        Model.modeIdAndArea m_modelIdAndArea = new Model.modeIdAndArea();
        private void comboBoxModeName_SelectedIndexChanged(object sender, EventArgs e)
        {     
            modeId = mydataDeal.modeNameToModeId(comboBoxModeName.Text);
            b_TCPComm.setModeId(modeId);
            comboBoxAutoModeArea.Items.Clear();
            mydataDeal.selectArea(modeId, comboBoxAutoModeArea);          //动态添加模式下的区域号

            //所有groupbox 不可见
            ButtonEnableOrVisable("groupBoxVisFalse");

            //根据模式判断模式下应有的 范围设定值文本 及设备显示
            //温度：最小值-最大值 ℃    风机 开 关
            int[] modeFac = mydataDeal.chkModeFac(modeId);
            int[] modeSensoe = mydataDeal.chkModeSensor(modeId);
            int temp;

            //设定范围值groupbox 宽和高
            int gourpBoxSetValueHeight = groupBoxSetValue.Size.Height;
            int groupBoxSetValueWeight = groupBoxSetValue.Size.Width;

            if (modeId == "1")
            {
                groupBoxPump.Location = new Point(32, 22);
                groupBoxSetValue.Size = new Size(289, 110);
                groupBoxControl.Size = new Size(289, 110);
                tabControlControl.Size = new Size(664, 220);
                groupBoxSoilHum.Location = new Point(10, 42);
                richTextBoxFacState.Size = new Size(641, 180);
                //groupBoxIll.Location = new Point(10, 42);
                this.Size = new Size(719, 480);
            }

            if (modeId == "2")
            {
                groupBoxSetValue.Size = new Size(289, 110);
                groupBoxControl.Size = new Size(289, 110);
                tabControlControl.Size = new Size(664, 220);
                groupBoxSoilHum.Location = new Point(10, 42);
                groupBoxPump.Location = new Point(32, 42);
                richTextBoxFacState.Size = new Size(641, 180);
                this.Size = new Size(719, 480);
            }

            if (modeId == "3")
            {
                groupBoxSetValue.Size = new Size(289, 224);
                groupBoxControl.Size = new Size(289, 224);
                tabControlControl.Size = new Size(664, 330);
                groupBoxPump.Location = new Point(32, 22);
                richTextBoxFacState.Size = new Size(641, 289);
                this.Size = new Size(719, 546);
            }


            for (int i = 0; i < modeFac.Length; i++)
            {
                temp = modeFac[i];

                //风机是否显示
                if (temp == 1)
                {
                    groupBoxFan.Visible = true;
                }

                //加热灯是否显示
                if (temp == 2)
                {
                    groupBoxHotLight.Visible = true;
                }

                //水泵是否显示
                if (temp == 3)
                {
                    groupBoxPump.Visible = true;
                }

                //天窗是否显示
                if (temp == 4)
                {
                    groupBoxWin.Visible = true;
                }

                //补光灯是否显示
                if (temp == 5)
                {
                    groupBoxLight.Visible = true;
                }
            }

            //循环读取对应模式下，监控的数据
            for (int i = 0; i < modeSensoe.Length; i++)
            {
                temp = modeSensoe[i];

                //MessageBox.Show(temp.ToString());
                //温度监控，最大值最小值设定框
                if (temp == 1)
                {
                    groupBoxTemp.Visible = true;
                    //MessageBox.Show("S1");
                }

                //空气湿度监控，最大值最小值设定框
                //if (temp == 2)
                //{                   
                //}

                //光照强度监控，最大值最小值设定框
                if (temp == 3)
                {
                    groupBoxIll.Visible = true;
                }

                ////土壤湿度监控，最大值最小值设定框
                if (temp == 4)
                {
                    groupBoxSoilHum.Visible = true;
                }

                //雨滴监控
                //if (temp == 5)
                //{
                //}
            }
        }

        private void butChooseMode_Click(object sender, EventArgs e)
        {
            if (butChooseMode.Text == "确认")
            {
                
                butChooseMode.Text = "重新选择模式";
                ButtonEnableOrVisable("确认");
            }
            else
            {
                ButtonEnableOrVisable("重新选择模式");
                butChooseMode.Text = "确认";                
            }
        }      

        //groupBox 去除边框
        private void groupBoxBianKuang(object sender, PaintEventArgs e)
        {
            e.Graphics.Clear(this.BackColor);
        }

        //groupBox  变绿色
        private void groupBoxFacility_Paint(object sender, PaintEventArgs e)
        {
            groupBox_RePaint(groupBoxFacility,e);
        }

        //groupBox  变绿色
        private void groupBoxDataShow_Paint(object sender, PaintEventArgs e)
        {
            groupBox_RePaint(groupBoxDataShow, e);
        }

        //groupBox  变绿色
        private void groupBoxControlCenter_Paint(object sender, PaintEventArgs e)
        {
            //groupBox_RePaint(groupBoxControlCenter, e);
        }

        //groupBox边框  变绿色
        private void groupBox_RePaint(GroupBox myGroupBox, PaintEventArgs e)
        {
            e.Graphics.Clear(myGroupBox.BackColor);
            e.Graphics.DrawString(myGroupBox.Text, myGroupBox.Font, Brushes.Green, 10, 1);
            e.Graphics.DrawLine(Pens.Green, 1, 7, 8, 7);
            e.Graphics.DrawLine(Pens.Green, e.Graphics.MeasureString(myGroupBox.Text, myGroupBox.Font).Width + 8, 7, myGroupBox.Width - 2, 7);
            e.Graphics.DrawLine(Pens.Green, 1, 7, 1, myGroupBox.Height - 2);
            e.Graphics.DrawLine(Pens.Green, 1, myGroupBox.Height - 2, myGroupBox.Width - 2, myGroupBox.Height - 2);
            e.Graphics.DrawLine(Pens.Green, myGroupBox.Width - 2, 7, myGroupBox.Width - 2, myGroupBox.Height - 2);

        }

        //点击按钮后，各个按钮显示或者改变值
        public void ButtonEnableOrVisable(string buttonText)
        {
            //窗体载入
            if (buttonText == "Form_Load")
            {
                butAutoModel.Enabled = false;                                               //窗口加载时禁用自动、手动模式按钮
                butManModel.Enabled = false;
                comboBoxAutoModeArea.Enabled = false;                                       //区域选择不可选择
                comboBoxModeName.Enabled = false;                                           //模式名称不可选择
                butChooseMode.Enabled = false;                                              //确认按钮不可选择

                //程序启动时，开关按钮、数据默认是不可点击的          
                butFanSwitch.Enabled = false;
                butWinSwitch.Enabled = false;
                butHotLigSwitch.Enabled = false;
                butLightSwitch.Enabled = false;
                butPumpSwitch.Enabled = false;

                //刷新区域按钮不可操作
                butFlashArea.Enabled = false;

                //默认值下拉框按钮不可选，清空按钮不可操作
                comboBoxDefault.Enabled = false;
                butCleanValue.Enabled = false;
            }

            //开启通讯/打开串口
            if (buttonText == "开启通讯")
            {
                butFlashArea.Enabled = true;                                           //开启通讯后刷新区域按钮可操作                   
                comboBoxModeName.Enabled = true;                                        //打开串口后，模式名称可选
                butChooseMode.Enabled = true;                                           //确认模式按钮可操作

                //未打开串口时模式下拉框可选，确认按钮可操作
                comboBoxModeName.Enabled = true;
                butChooseMode.Enabled = true;

                //自动区域
                textBoxTempMin.Enabled = true;
                textBoxTempMax.Enabled = true;
                textBoxIllMin.Enabled = true;
                textBoxIllMax.Enabled = true;
                textBoxSoilHumMin.Enabled = true;
                textBoxSoilHumMax.Enabled = true;

                //默认值下拉框按钮不可选，清空按钮不可操作
                comboBoxDefault.Enabled = true;
                butCleanValue.Enabled = true;
            }

            //关闭通讯/关闭串口
            if (buttonText == "关闭通讯")
            {
                butFlashArea.Enabled = false;                                               //关闭通讯后刷新区域按钮不可操作
                butAutoModel.Enabled = false;                                               //窗口加载时禁用自动模式按钮
                butManModel.Enabled = false;
                comboBoxAutoModeArea.Enabled = false;
                
                //选择模式按钮文本变更
                butChooseMode.Text = "确认";

                //未打开串口时模式下拉框不可选，确认按钮不可操作
                comboBoxModeName.Enabled = false;
                butChooseMode.Enabled = false;

                //自动区域不可选
                textBoxTempMin.Enabled = false;
                textBoxTempMax.Enabled = false;
                textBoxIllMin.Enabled = false;
                textBoxIllMax.Enabled = false;
                textBoxSoilHumMin.Enabled = false;
                textBoxSoilHumMax.Enabled = false;
            }

            //开启自动模式
            if (buttonText == "开启自动模式")
            {
                //开启自动模式后，自动模式范围值设定文本不可填
                ButtonEnableOrVisable("autoValueTextVisableFlase");

                //默认值下拉框按钮不可选，清空按钮不可操作
                comboBoxDefault.Enabled = false;
                butCleanValue.Enabled = false;

                //开启自动模式后，手动模式开关不可用
                butFanSwitch.Enabled = false;
                butWinSwitch.Enabled = false;
                butHotLigSwitch.Enabled = false;
                butLightSwitch.Enabled = false;
                butPumpSwitch.Enabled = false;

                //开启自动模式后，自动模式域号下拉框不可选
                //comboBoxAutoModeArea.Enabled = false;
                //开启自动模式后，开启手动模式按钮不可操作
                butManModel.Enabled = false;
                //开启自动模式后，开启通讯按钮不可操作
                butOpenCom.Enabled = false;
                //开启自动模式后，刷新区域号按钮不可操作
                butFlashArea.Enabled = false;

                ButtonEnableOrVisable("autoValueTextVisableFlase");                
            }

            //关闭自动模式
            if (buttonText == "关闭自动模式")
            {
                //关闭自动模式后，自动模式范围值设定文本可填
                ButtonEnableOrVisable("autoValueTExtVisableTrue");

                //默认值下拉框按钮可选，清空按钮可操作
                comboBoxDefault.Enabled = true;
                butCleanValue.Enabled = true;

                //关闭自动模式后，自动模式域号下拉框可选
                comboBoxAutoModeArea.Enabled = true;
                //关闭自动模式后，开启手动模式按钮可操作
                butManModel.Enabled = true;
                //关闭自动模式后，开启通讯按钮可操作
                butOpenCom.Enabled = true;

                ButtonEnableOrVisable("autoValueTExtVisableTrue");

            }

            //自动控制范围值文本框不可编辑
            if (buttonText == "autoValueTextVisableFlase")
            {
                //自动范围设定值文本框不可操作
                textBoxTempMin.Enabled = false;
                textBoxTempMax.Enabled = false;
                textBoxIllMin.Enabled = false;
                textBoxIllMax.Enabled = false;
                textBoxSoilHumMin.Enabled = false;
                textBoxSoilHumMax.Enabled = false;
            }

            if (buttonText == "autoValueTExtVisableTrue")
            {
                //若此区域未被开启模式，则文本框可操作
                textBoxTempMin.Enabled = true;
                textBoxTempMax.Enabled = true;
                textBoxIllMin.Enabled = true;
                textBoxIllMax.Enabled = true;
                textBoxSoilHumMin.Enabled = true;
                textBoxSoilHumMax.Enabled = true;
            }

            if (buttonText == "开启手动模式")
            {
                //开启手动模式后，自动模式下范围值设定文本框不可填
                ButtonEnableOrVisable("autoValueTextVisableFlase");
                butFlashArea.Enabled = false;                          //开启手动模式后，刷新区域号按钮不可操作
                //
                comboBoxAutoModeArea.Enabled = false;
                //自动模式按钮不可操作
                butAutoModel.Enabled = false;
                //打开串口按钮不可操作
                butOpenCom.Enabled = false;


                //开关可操作
                butFanSwitch.Enabled = true;
                butWinSwitch.Enabled = true;
                butHotLigSwitch.Enabled = true;
                butPumpSwitch.Enabled = true;
                butLightSwitch.Enabled = true;

            }

            if (buttonText == "关闭手动模式")
            {
                //关闭手动模式，自动模式下设定范围值文本框可填
                ButtonEnableOrVisable("autoValueTExtVisableTrue");

                //关闭手动模式，各个开关不可操作
                butFanSwitch.Enabled = false;
                butWinSwitch.Enabled = false;
                butHotLigSwitch.Enabled = false;
                butLightSwitch.Enabled = false;
                butPumpSwitch.Enabled = false;

                comboBoxAutoModeArea.Enabled = true;
                //自动模式按钮可操作
                butAutoModel.Enabled = true;
                //打开串口按钮可操作
                butOpenCom.Enabled = true;
            }

            //所有groupbox 不可见
            if (buttonText == "groupBoxVisFalse")
            {
                groupBoxTemp.Visible = false;
                groupBoxIll.Visible = false;
                groupBoxSoilHum.Visible = false;

                groupBoxFan.Visible = false;
                groupBoxHotLight.Visible = false;
                groupBoxLight.Visible = false;
                groupBoxWin.Visible = false;
                groupBoxPump.Visible = false;
            }

            //确认模式后
            if (buttonText == "确认")
            {
                comboBoxModeName.Enabled = false;
                butAutoModel.Enabled = true;                                           //打开串口后，自动、手动模式可操作           
                butManModel.Enabled = true;
                comboBoxAutoModeArea.Enabled = true;
            }

            //重新选择模式
            if (buttonText == "重新选择模式")
            {
                butAutoModel.Enabled = false;                                           //打开串口后，自动、手动模式不可操作           
                butManModel.Enabled = false;
                comboBoxAutoModeArea.Enabled = false;
                comboBoxModeName.Enabled = true;
            }
        }

        private void comboBoxDefault_SelectedIndexChanged(object sender, EventArgs e)
        {
            textBoxTempMin.Clear();
            textBoxTempMax.Clear();
            textBoxSoilHumMin.Clear();
            textBoxSoilHumMax.Clear();
            textBoxIllMin.Clear();
            textBoxIllMax.Clear();

            switch (comboBoxDefault.Text.Trim())
            {
                case "采摘期": 
                    textBoxTempMin.Text = "20"; textBoxTempMax.Text = "26";
                    textBoxSoilHumMin.Text = "20";textBoxSoilHumMax.Text = "3";
                    textBoxIllMin.Text = "70";textBoxIllMax.Text = "135";
                    break;
                case "播种期":
                    textBoxTempMin.Text = "25"; textBoxTempMax.Text = "35";
                    textBoxSoilHumMin.Text = "35"; textBoxSoilHumMax.Text = "45";
                    textBoxIllMin.Text = "80"; textBoxIllMax.Text = "120";
                    break;
                case "发芽期":
                    textBoxTempMin.Text = "20"; textBoxTempMax.Text = "26";
                    textBoxSoilHumMin.Text = "50"; textBoxSoilHumMax.Text = "60";
                    textBoxIllMin.Text = "100"; textBoxIllMax.Text = "120";
                    break;
                case "生长期":
                    textBoxTempMin.Text = "16"; textBoxTempMax.Text = "30";
                    textBoxSoilHumMin.Text = "43"; textBoxSoilHumMax.Text = "65";
                    textBoxIllMin.Text = "80"; textBoxIllMax.Text = "100";
                    break;
                case "开花期":
                    textBoxTempMin.Text = "18"; textBoxTempMax.Text = "28";
                    textBoxSoilHumMin.Text = "45"; textBoxSoilHumMax.Text = "60";
                    textBoxIllMin.Text = "90"; textBoxIllMax.Text = "125";
                    break;
                case "结果期":
                    textBoxTempMin.Text = "17"; textBoxTempMax.Text = "33";
                    textBoxSoilHumMin.Text = "50"; textBoxSoilHumMax.Text = "60";
                    textBoxIllMin.Text = "80"; textBoxIllMax.Text = "130";
                    break;
                case "成熟期":
                    textBoxTempMin.Text = "20"; textBoxTempMax.Text = "33";
                    textBoxSoilHumMin.Text = "43"; textBoxSoilHumMax.Text = "60";
                    textBoxIllMin.Text = "90"; textBoxIllMax.Text = "127";
                    break;
            }
        }

        private void butCleanValue_Click(object sender, EventArgs e)
        {
            textBoxTempMin.Clear();
            textBoxTempMax.Clear();
            textBoxSoilHumMin.Clear();
            textBoxSoilHumMax.Clear();
            textBoxIllMin.Clear();
            textBoxIllMax.Clear();
        }

        private void textBoxSerIP_MouseClick(object sender, MouseEventArgs e)
        {
            textBoxSerIP.Clear();
        }

        private void textBoxPort_MouseClick(object sender, MouseEventArgs e)
        {
            textBoxPort.Clear();
        }

        private void butDataAny_Click(object sender, EventArgs e)
        {
            weatherDataAny myWeather = new weatherDataAny();
            myWeather.Show();
        }

    }    
}
